import { login, logout, getInfo } from '@/api/login';
import { setToken, removeToken } from '@/utils/auth';
import { removeTenantId } from '../../utils/auth';
import { tipsBar } from '../../utils/jk/jk-tool';
import { MessageBox } from 'element-ui';

const user = {
  state: {
    id: 0, // 用户编号
    name: '',
    avatar: '',
    roles: [],
	  empInfo: {},
	  nickname: '',
    permissions: [],
	  userWorkshop: {},
	  userGroup: {},
	  userProcess: {}
  },

  mutations: {
    SET_ID: (state, id) => {
      state.id = id;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_NICKNAME: (state, nickname) => {
      state.nickname = nickname;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
	  // 用户绑定的员工信息
	  SET_EMP_INFO: (state, payload) => {
		  state.empInfo = payload;
	  }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const captchaVerification = userInfo.captchaVerification;
      const socialCode = userInfo.socialCode;
      const socialState = userInfo.socialState;
      const socialType = userInfo.socialType;
      return new Promise((resolve, reject) => {
        login(username, password, userInfo.invalidType, captchaVerification, socialType, socialCode, socialState, false).then(res => {
	        if (res.data.status === 200) {
		        resolve();
		        res = res.data.res;
		        // 设置 token
		        setToken(res);
	        } else if (res.data.status === 406) {
		        MessageBox({
			        title: '消息',
			        message: `该账号正在使用,确认继续登录 ？`,
			        iconClass: 'el-icon-question',
			        showCancelButton: true,
			        confirmButtonText: '确定',
			        cancelButtonText: '取消',
			        beforeClose: (action, instance, done) => {
				        if (action === 'confirm') {
					        instance.confirmButtonLoading = true;
					        instance.confirmButtonText = '执行中...';
					        login(username, password, userInfo.invalidType, captchaVerification, socialType, socialCode, socialState, true).then(res => {
						        instance.confirmButtonLoading = false;
						        instance.confirmButtonText = '确定';
						        if (res.data.status === 200) {
							        resolve();
							        res = res.data.res;
							        setToken(res);
							        done();
						        }
					        });
				        } else {
					        reject(res);
					        done();
				        }
			        }
		        }).then(() => {}).catch(() => {});
	        } else {
		        reject(res);
	        }
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          // 没有 data 数据，赋予个默认值
          if (!res.data.res) {
            res = {
              data: {
                roles: [],
                user: {
                  id: '',
                  avatar: '',
                  userName: '',
                  nickname: ''
                },
	              group: {},
	              workshop: {}
              }
            };
          }
          const resData = JSON.parse(JSON.stringify(res.data.res));
          const empInfo = res.data.res.emp ? res.data.res.emp : {};
	        commit('SET_EMP_INFO', empInfo);
	        resData.workshop.workshopList = resData.workshop.workshops.map(x => {
				return {
					id: x.workshopId,
					code: x.workshopCode,
					name: x.workshopName
				};
	        });
	        resData.workshop.workshopList = resData.workshop.workshopList.filter(x => x.code !== 'TOTAL_WORKSHOP');
		        resData.group.groupList = resData.group.groups.map(x => {
		        return {
			        id: x.groupId,
			        code: x.groupCode,
			        name: x.groupName
		        };
	        });
	        resData.process.processList = resData.process.processList.map(x => {
		        return {
			        id: x.processId,
			        code: x.processCode,
			        name: x.processName,
			        ifScheduling: x.ifScheduling,
			        ifReport: x.ifReport,
			        workshopId: x.workshopId,
			        workshopCode: x.workshopCode,
			        workshopName: x.workshopName
		        };
	        });
	        state.userWorkshop = resData.workshop;
	        state.userGroup = resData.group;
	        state.userProcess = resData.process;

          res = res.data.res;
          const user = res.user;
          const avatar = (user.avatar === '' || user.avatar == null) ? require('../../assets/images/default-avatar.png') : user.avatar;
	        commit('SET_PERMISSIONS', res.permissions || []);
	        if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.roles);
            // commit('SET_PERMISSIONS', res.permissions);
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT']);
          }
          commit('SET_ID', user.id);
          commit('SET_NAME', user.userName);
          commit('SET_NICKNAME', user.nickname);
          commit('SET_AVATAR', avatar);
          resolve(res);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 退出系统
    LogOut({ commit, dispatch, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_ROLES', []);
          commit('SET_PERMISSIONS', []);
	        dispatch('tagsView/delAllVisitedViews');
	        removeToken();
	        removeTenantId();
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    }
  }
};

export default user;
